/**
 * 02/nov/2011
 */
package edu.android;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;

/**
 * @author fabiomelillo@gmail.com
 *
 */
public class MyMoviesContentProvider extends ContentProvider {
	
	private MoviesDB db;
	public static final Uri CONTENT_URI = MovieMetaData.CONTENT_URI;
	

	/* (non-Javadoc)
	 * @see android.content.ContentProvider#delete(android.net.Uri, java.lang.String, java.lang.String[])
	 */
	@Override
	public int delete(Uri uri, String where, String[] whereArgs) {
		if (uri.equals(CONTENT_URI)){
			
			int toReturn=db.deleteMovies(where, whereArgs);
			return toReturn;
		}
		return 0;
	}

	/* (non-Javadoc)
	 * @see android.content.ContentProvider#getType(android.net.Uri)
	 */
	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see android.content.ContentProvider#insert(android.net.Uri, android.content.ContentValues)
	 */
	@Override
	public Uri insert(Uri uri, ContentValues values) {
		if (uri.equals(CONTENT_URI)){
			String regista=values.getAsString(MovieMetaData.MOVIE_DIRECTOR_KEY);
			String titolo=values.getAsString(MovieMetaData.MOVIE_TITLE_KEY);
			String year=values.getAsString(MovieMetaData.MOVIE_YEAR_KEY);
			Integer rate=values.getAsInteger(MovieMetaData.MOVIE_RATE_KEY);
			if (rate==null) rate=0;
			Integer seen=values.getAsInteger(MovieMetaData.MOVIE_SEEN_KEY);
			if (seen==null) seen=0;
			Integer hd=values.getAsInteger(MovieMetaData.MOVIE_HD_KEY);
			if (hd==null) hd=0;
			Movie movie=new Movie(titolo, regista, year, seen, hd, rate);
			Uri toReturn=db.insertMovie(movie);
			return toReturn;
		}
		return null;
	}

	/* (non-Javadoc)
	 * @see android.content.ContentProvider#onCreate()
	 */
	@Override
	public boolean onCreate() {
		db=(new MoviesDB(getContext()));
		return db.open();
	}

	/* (non-Javadoc)
	 * @see android.content.ContentProvider#query(android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String)
	 */
	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		
		
		SQLiteQueryBuilder qb=new SQLiteQueryBuilder();
		qb.setTables(db.getTableName());
		
		Cursor c=qb.query(db.getSQLiteDatabase(), projection, selection, selectionArgs, null, null, sortOrder);
		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;
	}

	/* (non-Javadoc)
	 * @see android.content.ContentProvider#update(android.net.Uri, android.content.ContentValues, java.lang.String, java.lang.String[])
	 */
	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		int toReturn = db.updateMovie(uri, values, selection, selectionArgs);
		return toReturn;
	}

}
